<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js透明度动画</title>
    <style>
        body,div,span{
            margin: 0;
            padding: 0;
        }
        div{
            width: 200px;
            height: 200px;
            background: red;
            margin-bottom: 20px;
            filter: opacity(30);
            opacity: .3;
        }
    </style>
    <script>
        window.onload = function(){
            console.log('window move');
            let oDiv = document.getElementsByTagName('div');
            for(item of oDiv){
                item.timer = null;
                item.alpha = 30;
                // 鼠标放置，开始外拉动画
                item.onmouseover = function() {
                    startMove(this, 100);
                }
                // 鼠标离开，开始收回动画
                item.onmouseleave = function() {
                    startMove(this, 30);
                }    
            }
        }
        function startMove(obj, iTarget) {
            // let oDiv = document.getElementById('div1');
            clearInterval(obj.timer);
            obj.timer = setInterval(function(){
                let speed = obj.alpha > iTarget? -10: 10;
                if(obj.alpha === iTarget){
                    clearInterval(obj.timer);
                } else{
                    obj.alpha += speed;
                    obj.style.filter = 'opacity('+obj.alpha+')'
                    obj.style.opacity = obj.alpha/100;
                }
            }, 30)
        }
    </script>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
</body>
</html>